const APP = '/lesson-admin';

onload = () => {
    // 添加一条用户记录
    let insertBtn = document.querySelector('#insertBtn');
    insertBtn.onclick = () => insertUser();
};

/*添加一条用户记录*/
function insertUser() {
    // 准备请求参数

    let gender = document.querySelector('input[name=gender]:checked').value;
    let username = document.querySelector('#usernameIpt').value;
    let password = document.querySelector('#passwordIpt').value;
    let realName = document.querySelector('#realNameIpt').value;
    let nickName = document.querySelector('#nickNameIpt').value;
    let age = document.querySelector('#ageIpt').value;
    let idCard = document.querySelector('#idCardIpt').value;
    let phone = document.querySelector('#phoneIpt').value;
    let createTime = document.querySelector('#createTimeIpt').value;
    let modifyTime = document.querySelector('#modifyTimeIpt').value;
    let userInfo = document.querySelector('#userInfoArea').value;


    // 判断必要参数不为空
    if (username && password && realName && nickName && gender && age &&
        idCard && phone && userInfo && createTime && modifyTime) {

        // 处理日期格式: 2023-08-12T15.26  -> 2020-02-01 12:12:12
        createTime = createTime.replace('T', ' ').replace('.', ':') + ':00';
        modifyTime = modifyTime.replace('T', ' ').replace('.', ':') + ':00';

        // 准备参数
        let data = {
            "username": username,
            "password": password,
            "real-name": realName,
            "nick-name": nickName,
            "gender": gender,
            "age": age,
            "id-card": idCard,
            "avatar-url": 'default-user-avatar.jpg', // 头像使用默认的
            "phone": phone,
            "user-info": userInfo,
            "create-time": createTime,
            "modify-time": modifyTime
        }
        // 发送添加用户请求
        ajax({
            'url': APP + `/api/v1/user/insert`,
            'type': 'post',
            'contentType': 'json',
            'data': data,
            'success': res => {
                if (res.code > 0) {
                    alert('添加成功!')
                    location.href = '../user/user.html';
                } else alert(res.message);
            }
        });
    } else alert('必要填写项为空，请检查！');
}